package com.zjh.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * @Auther: zjh
 * @Date: 2025/9/26 - 09 - 26 - 8:17
 * @Description: com.zjh.config
 * @version: 1.0
 */
@Slf4j
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    public UserDetailsService userDetailsService() {
        log.error("userDetailsService");
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withDefaultPasswordEncoder().username("admin").password("123").roles("ADMIN","USER").build());
        inMemoryUserDetailsManager.createUser(User.withDefaultPasswordEncoder().username("user").password("123").roles("USER").build());
        inMemoryUserDetailsManager.createUser(User.withDefaultPasswordEncoder().username("zjh").password("123").authorities("READ_INFO").build());
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .mvcMatchers("/admin").hasRole("ADMIN")
                .mvcMatchers("/user").hasRole("USER")
                .mvcMatchers("/getInfo").hasAuthority("READ_INFO")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .csrf().disable();
//        http.authorizeRequests()
//                .mvcMatchers("/admin")
//                .access("hasRole('ADMIN') and principal.username == 'boss'")
    }
}
